package com.card.hwatt.service.impt;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.card.hwatt.dao.*;
import com.card.hwatt.dto.PageParam;
import com.card.hwatt.entity.*;
import com.card.hwatt.service.*;

@Service("scheduleService")
public class ScheduleServiceImpt extends BaseServiceImpt<Schedule> implements
		ScheduleService {

	@Autowired
	@Qualifier("scheduleDao")
	private ScheduleDao dao;

	@Autowired
	@Qualifier("nightCheckDao")
	private NightCheckDao nightCheckDao;

	@Override
	protected BaseDao<Schedule> getDao() {
		return dao;
	}

	@Override
	public void save(Schedule entity) {
		if (entity.id != null) {
			dao.delete(entity.id);
		}
		entity.id = UUID.randomUUID();
		dao.save(entity);

		if (entity.night != null
				&& CollectionUtils.isNotEmpty(entity.nightCheckList)) {
			for (NightCheck item : entity.nightCheckList) {
				nightCheckDao.save(item);
			}
		}
	}

	@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
	public Schedule get(String date, Long departmentId) {
		if (StringUtils.isEmpty(date)) {
			return null;
		}
		Date start = null;
		try {
			String[] parsePatterns = { "yyyy-MM-dd", "yyyy-M-dd", "yyyy-M-d" };
			start = DateUtils.parseDate(date, parsePatterns);
		} catch (Exception e) {
			return null;
		}

		List<Object> params = new ArrayList<Object>();

		params.add(departmentId);
		params.add(new java.sql.Date(start.getTime()));
		params.add(new java.sql.Date(start.getTime()));

		List<Schedule> result = this
				.loadAll(new PageParam(
						1,
						1,
						" department is not null and department.id = ? and startDate <= ? and endDate >= ? ",
						params, " startDate desc ")).rows;

		if (!CollectionUtils.isEmpty(result)) {
			return result.get(0);
		}

		params.clear();
		params.add(new java.sql.Date(start.getTime()));
		params.add(new java.sql.Date(start.getTime()));

		result = this.loadAll(new PageParam(1, 1,
				" department is null and startDate <= ? and endDate >= ? ",
				params, " startDate desc ")).rows;

		return CollectionUtils.isEmpty(result) ? null : result.get(0);
	}
}
